<template>
	<div class="app-container" v-loading="loading">

		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="4">
						<el-tree-select  v-model="queryParams.cid" clearable
							:data="baseConfigStore.newExCompanyList" check-strictly :render-after-expand="false"
							placeholder="请选择所属公司">
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入项目名称" clearable
							@keyup.enter="handleQuery" />
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.subject" placeholder="请输入贷款主体" clearable
							@keyup.enter="handleQuery" />
					</el-col>
					<el-col :span="6">
						<el-button :loading="loading" type="primary" @click="handleQuery"><template
								#icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" :strtype="strtype"></FilterColumn>
			</div>
		</div>

		<el-card shadow="never">
			<div class="action-row">
				<el-button v-hasPerm="['Financing/save']" type="primary" @click="handleDo('','act_add')" plain><template
						#icon><i-ep-plus /></template>新增</el-button>
				<el-button @click="handleDo('', 'act_info')" :disabled="multipleSelection.length !== 1"
					:type="buttonType(multipleSelection.length)" plain><template
						#icon><i-ep-document /></template>详情</el-button>
				<el-button v-hasPerm="['Financing/update']" @click="handleDo('', 'act_edit')"
					:disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)"
					plain><template #icon><i-ep-edit /></template>修改</el-button>
				<el-button v-hasPerm="['Financing/delete']" @click="handleDo('', 'act_del')"
					:disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)"
					plain><template #icon><i-ep-delete /></template>删除</el-button>
				<el-button v-hasPerm="['FinancingLog']" :disabled="multipleSelection.length !== 1"
					:type="buttonType(multipleSelection.length)" @click="handleDo('','act_loan')" plain><template
						#icon><i-ep-discount /></template>放款记录</el-button>
			</div>
			<el-table ref="dataTableRef" v-loading="loading" :data="tableData" align="left" tooltip-effect="dark"
				:show-overflow-tooltip="true" :scrollbar-always-on="true" border @cell-mouse-enter="rowMouse"
				@cell-mouse-leave="menuLineVisible=false" @selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="55" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width"
						:min-width="item.minwidth">
						<template #default="scope" v-if="item.prop == 'name'">
							<el-link @click="handleDo(scope.row,'act_info')" type="primary">{{scope.row.name}}</el-link>

						</template>
						<template #default="scope" v-if="item.prop == 'juxiandaoqiriqi'">
							<el-text
								type="danger">{{daysBetweenDates(scope.row.start_date,scope.row.end_date)}}</el-text>
						</template>
						<template #default="scope" v-if="item.prop == 'is_implicit'">
							{{scope.row.is_implicit == 1?"是":"否"}}
						</template>
						<template #default="scope" v-if="item.prop == 'files'">
							<template v-if="scope.row.files.length>0">
								<el-link @click="handleDo(scope.row,'act_info')" type="primary">
									{{scope.row.files.length}}<template #icon><i-ep-link /></template>附件</el-link>
							</template>
							<el-link v-else type="info">无</el-link>
						</template>
					</el-table-column>
				</template>

			</el-table>
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>

		<!-- 添加or编辑信息or 查看详情 -->
		<financingEdit ref="financingEditRef" @initRefreshList="handleQuery"></financingEdit>

		<!-- 放款记录 -->
		<loanRecords ref="loanRecordsRef" @initRefreshList="handleQuery">></loanRecords>

	</div>
</template>
<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { daysBetweenDates } from "@/utils/funcall"
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	import { useUserStore } from "@/store/modules/user";
	import { useTableFilterStore } from "@/store/modules/tableFilter";
	import financingEdit from "./components/financingEdit.vue"
	import loanRecords from "./components/LoanRecords.vue"
	// 获取接口地址
	import {
		getFinancingList
	} from "@/api/financing"
	// 表格数据
	const userStore = useUserStore();
	const TableFilter = useTableFilterStore();
	const baseConfigStore = useBaseConfigStore();
	const strtype = ref('financing'); //数据

	// 表格标题
	const cTitles = ["项目名称", "贷款主体", "机构名称", "贷款年限", "贷款起始日", "贷款终止日", "距现到期日期", "年利率", "担保方式", "协议金额", "余额", "是否隐形债务", "付息方式", "附件","添加人","添加时间"];
	// 显示字段
	const sTitles = ["项目名称", "贷款主体", "机构名称", "贷款年限", "贷款起始日", "贷款终止日", "距现到期日期","添加人","添加时间"];
	// 字段属性
	const cColumns = [

		{ label: "项目名称", prop: "name", align: "center", minwidth: 200 },
		{ label: "贷款主体", prop: "subject", align: "center", minwidth: 200 },
		{ label: "机构名称", prop: "agency", align: "center", minwidth: 200 },
		{ label: "贷款年限", prop: "year", align: "center", width: 100 },
		{ label: "贷款起始日", prop: "start_date", align: "center", minwidth: 150 },
		{ label: "贷款终止日", prop: "end_date", align: "center", minwidth: 150 },
		{ label: "距现到期日期", prop: "juxiandaoqiriqi", align: "center", minwidth: 150 },
		{ label: "年利率", prop: "rate", align: "center", minwidth: 100 },
		{ label: "担保方式", prop: "danbao", align: "center", minwidth: 150 },
		{ label: "协议金额", prop: "money", align: "center", minwidth: 150 },
		{ label: "余额", prop: "balance", align: "center", minwidth: 150 },
		{ label: "是否隐形债务", prop: "is_implicit", align: "center", minwidth: 130 },
		{ label: "付息方式", prop: "interest_type", align: "center", minwidth: 150 },
		{ label: "附件", prop: "files", align: "center", minwidth: 200 },
		{ label: "添加人", prop: "user.name", align: "center", minwidth: 120 },
		{ label: "添加时间", prop: "add_time_text", align: "center", minwidth: 200 }
	]

	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}
	

	const loanRecordsRef = ref();//放款列表
	const financingEditRef = ref();//添加编辑-修改-删除

	/*** 搜索窗-字段表 */
	const queryParams = reactive({
		page: 1,
		limit: 20,
		cid: "",
		name: "",//项目名称
		subject: ""//贷款主体
	});
	const loading = ref(false);//页面加载load
	const total = ref(0);
	const tableData = ref<any>();
	const multipleSelection = ref<any>([]);
	const menuLineVisible = ref(true);
	const rowR = ref<any>({});


	// 行菜单事件
	function rowMouse(row : any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val : any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val : any) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	// 初始化搜索内容
	async function handleQuery() {
		loading.value = true;
		getFinancingList(queryParams).then((res) => {
			tableData.value = res.data.list
			total.value = res.data.count
		}).finally(() => {
			loading.value = false;
		})
	}
	// 重置搜索内容
	function resetQuery() {
		handleQuery();
	}


	// 打开新增表单内容
	function handleDo(row ?: any, act ?: string,) {
		switch (act) {
			case 'act_add':
				financingEditRef.value.handleShow({}, act)
				break
			case 'act_loan':
				loanRecordsRef.value.handleShow(row || multipleSelection.value[0], act)
				break
			default:
				financingEditRef.value.handleShow(row || multipleSelection.value[0], act)
		}
	}

	onMounted(() => {
		handleQuery();
		columnsInit();
	});
</script>

<style lang="scss" scoped>

</style>